// miniprogram/pages/index/index.js
//采用MQTT协议
// import { connect } from 'mqtt'
const mqtt = require("../../utils/mqtt")
const connect = mqtt.connect

const app = getApp()
const gb = app.globalData
const wxp = gb.wxp

//服务器接口
const MqttConnect = 'wxs://stm32.mqtt-8266.xyz:8084/mqtt'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    client: {},
    temperature: 0,
    humidity: 0,
    ppm: 0,
    led: false,
    lock: false,
    area: '请求中',//城区
    city: '请求中',//城市
    airText: '请求中',//空气质量
    airValue: 0,//空气指数
    weather: '请求中',//天气
    weatherAdvice: '请求中'//天气建议
  },

  // 门禁
  LockStatus: function (event) {
    //console.log(event)
    let sw = event.detail.value
    this.data.lock = sw
    if (sw) {
      gb.client.publish('SmartHome', '{"target":"LOCK","value":1}', function (err) {
        if (!err)
          console.log("成功开门")
      })
    }
    else {
      gb.client.publish('SmartHome', '{"target":"LOCK","value":0}', function (err) {
        if (!err)
          console.log("已关门")
      })
    }
  },

  // LED
  // TODO
  LedStatus: function (event) {
    let sw = event.detail.value
    this.data.led = sw
    if (sw) {
      gb.client.publish('SmartHome', '{"target":"LED","value":1}', function (err) {
        if (!err)
          console.log("成功开灯")
      })
    }
    else {
      gb.client.publish('SmartHome', '{"target":"LED","value":0}', function (err) {
        if (!err)
          console.log("成功关灯")
      })
    }
  },

  // 空调
  // TODO
  AirStatus: function (event) {
    let sw = event.detail.value
    this.data.led = sw
    if (sw) {
      //2位的数据控制
      gb.client.publish('SmartHome', '{"target":"control","value":3}', function (err) {
        if (!err)
          console.log("成功开语音控制")
      })
    }
    else {
      gb.client.publish('SmartHome', '{"target":"control","value":0}', function (err) {
        if (!err)
          console.log("成功关语音控制")
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     wx.hideHomeButton({})

    // 获取mqtt实例
    // if (gb.client == '') {
    //   gb.clientCallback = res => {
    //     this.setData({ client: gb.client })
    //   }
    // } else {
    //   // this.setData({ client: gb.client })
    //   this.data.client = gb.client
    // }

    // 得到硬件信息
    gb.client.on('message', (topic, message) => {
      console.log(topic)
      //message打印不会转成字符串,而是16进制数据
      let data_switch = {}
      data_switch = JSON.parse(message)
      /*对上行数据进行处理*/
      this.setData({
        temperature: data_switch.temperature,
        humidity: data_switch.humidity,
        ppm:  data_switch.ppm
      })
      /* 前端下行数据 */
    })

    // 获取定位
    wxp.getLocation({ type: 'wgs84' })
      .then(res => {
        console.log(res)
        const latitude = res.latitude
        const longitude = res.longitude
        const key = '8764f0013a2e401784b402743ef3740b'

        wx.request({
          url: `https://geoapi.heweather.net/v2/city/lookup?location=${longitude},${latitude}&key=${key}`, //获取位置信息
          success: res => {
            const { adm2, name } = res.data.location[0]
            this.setData({
              area: name,
              city: adm2
            })
          }
        })

        wx.request({
          url: `https://devapi.heweather.net/v7/weather/now?location=${longitude},${latitude}&key=${key}`, //获取天气数据API接口
          success: res => {
            this.setData({ weather: res.data.now.text })
          }
        })

        wx.request({
          url: `https://devapi.heweather.net/v7/air/now?location=${longitude},${latitude}&key=${key}`, //
          success: res => {
            let { aqi, category } = res.data.now
            this.setData({
              airText: category,
              airValue: aqi
            })
          }
        })

        wx.request({
          url: `https://devapi.heweather.net/v7/indices/1d?type=6&location=${longitude},${latitude}&key=${key}`, //获取位置信息
          success: res => {
            this.setData({
              weatherAdvice: res.data.daily[0].text
            })
          }
        })
      })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})